<template>
  <a-upload accept=".txt" :custom-request="customRequest" :show-upload-list="false">
    <a-button type="primary" :loading="loading">导入TXT</a-button>
  </a-upload>
</template>

<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import axios from 'axios'

const props = defineProps({
  uploadUrl: {
    type: String,
    default: ''
  },
  searchParams: {
    type: Object,
    default: () => ({})
  },
  type: {
    type: String,
    default: '西成药'
  }
})
const emit = defineEmits(['success'])
const parameters = ref({})
const loading = ref(false)
const customRequest = async (options) => {
  const { file } = options
  const isJpgOrPng = file.type === 'text/plain'
  if (!isJpgOrPng) {
    message.error('请上传TXT格式文件!')
    return
  }
  const isLt2M = file.size / 1024 / 1024 < 20
  if (!isLt2M) {
    message.error('上传文件最大20MB!')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  loading.value = true
  const { data: res } = await axios.post(props.uploadUrl, formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  loading.value = false
  emit('success')
}
watch(
  () => props.searchParams,
  (val) => {
    const { dateRange, ...rest } = val
    parameters.value = {
      ...rest,
      ...(dateRange && { stdate: dateRange[0], eddate: dateRange[1] })
    }
  },
  { deep: true, immediate: true }
)
</script>
<style lang="less" scoped></style>
